package compendiumAid.application.exportElements
{
	import compendiumAid.domain.Constants;
	import compendiumAid.domain.model.ApplicationModel;
	
	import flash.events.Event;
	import flash.filesystem.File;
	import flash.filesystem.FileMode;
	import flash.filesystem.FileStream;
	import flash.geom.Rectangle;
	import flash.utils.ByteArray;
	
	import mx.collections.ArrayCollection;
	import mx.controls.Alert;
	import mx.graphics.BitmapFill;
	import mx.graphics.SolidColor;
	import mx.managers.CursorManager;
	
	import org.alivepdf.colors.IColor;
	import org.alivepdf.colors.RGBColor;
	import org.alivepdf.display.Display;
	import org.alivepdf.images.ColorSpace;
	import org.alivepdf.layout.Layout;
	import org.alivepdf.layout.Mode;
	import org.alivepdf.layout.Orientation;
	import org.alivepdf.layout.Position;
	import org.alivepdf.layout.Resize;
	import org.alivepdf.layout.Size;
	import org.alivepdf.layout.Unit;
	import org.alivepdf.pages.Page;
	import org.alivepdf.pdf.PDF;
	import org.alivepdf.saving.Download;
	import org.alivepdf.saving.Method;
	import org.spicefactory.lib.task.Task;
	
	import spark.components.HGroup;
	import spark.primitives.Rect;

	public class ExportElementsTask extends Task
	{
		private static const WIDTH:uint  = 0;
		private static const HEIGHT:uint = 1;
		
		private var elementRows:ArrayCollection;
		private var model:ApplicationModel;
		private var file:File;
		
		public function ExportElementsTask(elementRows:ArrayCollection, model:ApplicationModel)
		{
			this.elementRows = elementRows;
			this.model = model;
			
			file = new File();
			file.addEventListener(Event.SELECT, exportElements);
		}
		
		override protected function doStart():void
		{
			file.browseForSave("Save the PDF to a directory of your choosing");
		}
		
		private function exportElements(event:Event):void
		{
			CursorManager.setBusyCursor();
			
			var printPDF:PDF = setupPDF();
			var resize:Resize = new Resize(Mode.FIT_TO_PAGE, Position.LEFT);
			
			var width:Number = getPrintableArea(WIDTH);
			var height:Number = getPrintableArea(HEIGHT);
			
			var totalHeight:Number = 0;
			var previousTotalHeight:Number = 0;
			
			var scale:Number;
			
			for each (var row:HGroup in elementRows)
			{
				scale = width / row.width;

				totalHeight += (row.height * scale);
				
				if (totalHeight > height)
				{
					printPDF.addPage(newPage);
					printPDF.setXY(0,0);
					previousTotalHeight = 0;
					totalHeight = (row.height * scale);
				}
				
				printPDF.addImage(row, resize, 0, previousTotalHeight);
				
				previousTotalHeight += totalHeight;
			}
			
			printPDF.end();
			
			if (saveToFile(printPDF) == true)
			{
				Alert.show("PDF Created", "File");
				
				file.openWithDefaultApplication();
			}
			
			CursorManager.removeBusyCursor();
			
			super.complete();
		}

		private function getPrintableArea(dimensionType:uint):Number
		{
			var dimension:Number;
			
			if (model.elementOrientation == Orientation.PORTRAIT)
			{
				if (dimensionType == WIDTH)
				{
					if (model.unitType == Unit.INCHES)
					{
						dimension = model.paperType.inchesSize[0];
					}
					else if (model.unitType == Unit.MM)
					{
						dimension = model.paperType.mmSize[0];
					}
				}
				else if (dimensionType == HEIGHT)
				{
					if (model.unitType == Unit.INCHES)
					{
						dimension = model.paperType.inchesSize[1];
					}
					else if (model.unitType == Unit.MM)
					{
						dimension = model.paperType.mmSize[1];
					}
				}
			}
			else
			{
				if (dimensionType == HEIGHT)
				{
					if (model.unitType == Unit.INCHES)
					{
						dimension = model.paperType.inchesSize[0];
					}
					else if (model.unitType == Unit.MM)
					{
						dimension = model.paperType.mmSize[0];
					}
				}
				else if (dimensionType == WIDTH)
				{
					if (model.unitType == Unit.INCHES)
					{
						dimension = model.paperType.inchesSize[1];
					}
					else if (model.unitType == Unit.MM)
					{
						dimension = model.paperType.mmSize[1];
					}
				}		
			}
			
			dimension = (dimension - (model.marginSize * 2))
			
			return dimension;
		}
		
		private function setupPDF():PDF
		{
			var pdf:PDF = new PDF(model.elementOrientation, model.unitType, model.paperType);
			
			pdf.setMargins(model.marginSize, model.marginSize, model.marginSize, model.marginSize);
			pdf.setDisplayMode(Display.FULL_PAGE, Layout.SINGLE_PAGE, Mode.FIT_TO_PAGE);
			pdf.addPage(newPage);
			
			return pdf;
		}
		
		private function get newPage():Page
		{
			return new Page(model.elementOrientation, model.unitType, model.paperType);
		}
		
		private function saveToFile(pdf:PDF):Boolean
		{
			var bytes:ByteArray = pdf.save(Method.LOCAL, "", Download.INLINE, file.name);
			
			try
			{
				var stream:FileStream = new FileStream();
				stream.open(file, FileMode.WRITE);
				stream.writeBytes(bytes);
				stream.close();
				
				return true;
			}
			catch (error:Error)
			{
				Alert.show("Error in saving file: " + error, "Error");
				return false;
			}
			
			return false;
		}
	}
}